<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 栅格布局 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 数据主体展示 -->
      <el-table
        stripe
        border
        :data="rolesList"
        row-key="id"
        :tree-props="{children: null, hasChildren: null}">
        <!-- 展开下拉项 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 通过栅格布局，展示权限等级的内容 -->
            <el-row
              v-for="item1 in scope.row.children"
              :key="item1.id"
              class="border-top"
            >
              <!-- 一级分类信息 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="delRightById(item1.id, scope.row)"
                >{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级、三级分类 -->
              <el-col :span="19">
                <el-row
                  v-for="item2 in item1.children"
                  :key="item2.id"
                  class="border-top"
                >
                  <!-- 二级分类的数据 -->
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="delRightById(item2.id, scope.row)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级分类的数据 -->
                  <el-col :span="16">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="delRightById(item3.id, scope.row)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="角色类型"
          prop="roleDesc"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="300px"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRights(scope.row)"
            >权限分配</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="rightsDialog"
      width="50%"
    >

      <!-- 展示树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="rightsDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="allotRigt"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rightsDialog: false,
      rightsList: [],
      // 指定树形结构内部的值和属性
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 需要一个数组，把 rightsList 里面三级分类的id放进来
      defKeys: [],
      // 即将分配权限的角色ID
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      let { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    async delRightById(id, role) {
      let res = await this.$confirm('确定删除权限嘛？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 这里代表用户点击的是取消
      if (res !== 'confirm') {
        return this.$message.info('取消操作啦~')
      }
      // 点击了确定按钮
      let { data: res1 } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      )
      if (res1.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      role.children = res1.data
    },
    async setRights(role) {
      this.roleId = role.id
      // 发请求得到数据，type类型为 tree 展示为树结构
      let { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('数据请求失败')
      this.rightsList = res.data
      // console.log(this.rightsList)

      this.defKeys = []
      // 当分配权限按钮触发点击事件，则会开启递归
      this.getLeafKey(role, this.defKeys)

      // 展示弹框
      this.rightsDialog = true
    },
    getLeafKey(node, arr) {
      // 需要把没有children属性的那一条数据的id push进数组中
      if (!node.children) {
        return arr.push(node.id)
      }
      // item 指的是一级、二级分类下的每分类
      node.children.forEach(item => {
        // 通过调用自己，继续向下执行
        this.getLeafKey(item, arr)
      })
    },
    async allotRigt() {
      // 1.0 得到全选和半选的数组
      const arr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      let arrStr = arr.join()

      // 2.0 发请求
      let { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: arrStr
      })
      if (res.meta.status !== 200) return this.$message.error('添加全先生失败')
      this.$message.success('添加权限成功')
      this.getRolesList()
      this.rightsDialog = false
    },
    setExpand(data) {
      data.forEach(item => {
        return item.id
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-table__expanded-cell {
  .el-row {
    margin-bottom: 15px;
    padding-top: 8px;
    display: flex;
    align-items: center;
    .el-col {
      div:first-child {
        border-top: none;
      }
    }
  }
  > .el-row {
    margin-bottom: 30px;
    padding-top: 10px;
  }
  .el-tag {
    margin: 7px;
  }
  > div:first-child {
    border-top: none;
  }
}

.border-top {
  border-top: 1px solid #eee;
}
</style>